﻿using AutoMapper;
using Domain.InvoiceTicket.Invoicing;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.InvoiceTicket.Invoice;
using ReturnValue;
using System.Transactions;

namespace MES.Server.API.Application.Handler.InvoiceTicket.Invoice
{
    public class InvoiceUpdateCommandHandler : IRequestHandler<InvoiceUpdateCommand, ApiResult<int>>
    {
        private readonly IRepository<InvoicingModel> _invoiceRepo;
        private readonly IRepository<OrderModel> _orderRepo;
        private readonly ILogger<InvoiceUpdateCommandHandler> _logger;

        public InvoiceUpdateCommandHandler(
            IRepository<InvoicingModel> invoiceRepo,
            IRepository<OrderModel> orderRepo,
            ILogger<InvoiceUpdateCommandHandler> logger)
        {
            _invoiceRepo = invoiceRepo;
            _orderRepo = orderRepo;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(InvoiceUpdateCommand request, CancellationToken cancellationToken)
        {
            // 使用事务确保数据一致性
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 获取要更新的发票
                    var invoice = await _invoiceRepo.GetValue(request.Id);
                    if (invoice == null)
                    {
                        return new ApiResult<int>().Fail("未找到对应的发票记录!");
                    } 

                    // 获取相关订单
                    var order = await _orderRepo.GetValue(request.OrderId);
                    if (order == null)
                    {
                        return new ApiResult<int>().Fail("未找到对应的订单记录!");
                    }

                    // 解析金额
                    if (!int.TryParse(request.InvoicingMomeny, out int newInvoiceAmount))
                    {
                        return new ApiResult<int>().Fail("发票金额格式不正确!");
                    }
                    
                    // 获取旧金额
                    int oldInvoiceAmount = invoice.InvoicingMomeny;

                    // 计算差额
                    int amountDifference = newInvoiceAmount - oldInvoiceAmount;

                    // 更新发票金额
                    invoice.InvoicingMomeny = newInvoiceAmount;
                    invoice.UpdaterPeople = "admin";
                    invoice.UpdateTime = DateTime.Now;
                    
                    // 更新订单已付金额
                    order.Tomomeny += amountDifference;
                    order.UpdaterPeople = "admin";
                    order.UpdateTime = DateTime.Now;

                    // 保存更改
                    var r1 = await _invoiceRepo.UpdateAsync(invoice);
                    var r2 = await _orderRepo.UpdateAsync(order);

                    tran.Complete();

                    if (r1 > 0 && r2 > 0)
                    {
                        return new ApiResult<int>().Success("更新成功!", r1 + r2);
                    }
                    else
                    {
                        return new ApiResult<int>().Fail("更新失败!");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"更新发票金额时发生异常: {ex.Message}");
                    return new ApiResult<int>().Fail($"更新失败: {ex.Message}");
                }
            }
        }
    }
}
